const Redis = require('ioredis');
const got = require('got');

const redis_key = 'spider_proxy_ip';

// 创建Redis客户端实例，指定主机和端口
const client = new Redis({
  host: '192.168.70.127',
  port: 6379, // 默认端口号
  password: 'Gridstar2023'
  // 如果有需要，可以提供密码和其他选项
});

// 写入列表
async function writeToRedisList(key, data) {
  try {
    // 使用 lpush 命令将数据写入列表中
    for (const item of data) {
      await client.lpush(key, JSON.stringify(item));
    }
    // 设置数据失效时间为5分钟（300秒）
    await client.expire(key, 300);
    return await client.lpop(key);
  } catch (error) {
    console.error('Error writing data to list:', error);
    return null;
  }
}

async function writeToRedisData(key, data, expireTime) {
  try {
    // 使用 lpush 命令将数据写入列表中
    await client.set(key, JSON.stringify(data));
    // 设置数据失效时间为5分钟（300秒）
    await client.expire(key, expireTime);
  } catch (error) {
    console.error('Error writing data to list:', error);
    return null;
  }
}

async function getToRedisData(key) {
  try {
    const data = await client.get(key);
    if (data) {
      return JSON.parse(data);
    }
    return '';
  } catch (error) {
    console.error('Error writing data to list:', error);
    return '';
  }
}

async function deleteToRedisData(key) {
  try {
    return await client.delete(key);
  } catch (error) {
    console.error('Error writing data to list:', error);
    return '';
  }
}

// 读取列表的某个数据
async function readFromRedisList(key) {
  try {
    // 使用 lpop 命令从列表左侧弹出一个元素
    const data = await client.lpop(key);
    return data;
  } catch (error) {
    console.error('Error reading data from list:', error);
    return null;
  }
}

async function request_spider_proxy() {
  try {
    let url = 'http://webapi.http.zhimacangku.com/getip?neek=1ebf4459c39b11b6&num=10&type=1&time=4&pro=0&city=0&yys=0&port=1&pack=0&ts=0&ys=0&cs=0&lb=1&sb=&pb=4&mr=3&regions=&cf=0';
    const resp = await got(url, {
      method: 'GET',
    });
    return resp.body;
  } catch (error) {
    console.log(error);
  }
}


//
async function getProxy() {
  let spider_data = await readFromRedisList(redis_key);
  if (spider_data == null || spider_data == '' || spider_data == undefined) {
    let spider_response_text = await request_spider_proxy();
    if (spider_response_text == null || spider_response_text == undefined || spider_response_text == '') {
      console.error('proxy response ip null');
      return '';
    }
    let spider_list = spider_response_text.split('\r\n');
    const spider_array = [];
    spider_list.forEach((item) => {
      if (item) {
        let spider = {
          ip: item.split(':')[0],
          port: Number(item.split(':')[1])
        };
        spider_array.push(spider);
      }
    });
    spider_data = await writeToRedisList(redis_key, spider_array);
  }
  if (spider_data == null) {
    throw new Error('spider_data is null');
  }
  const data = JSON.parse(spider_data);
  const ip = data.ip;
  const port = data.port;
  const proxyUrl = `http://${ip}:${port}`;
  console.log('proxyUrl',proxyUrl);
  return proxyUrl;
}

module.exports = {
  getProxy,
  writeToRedisData,
  getToRedisData,
  deleteToRedisData
};
